import { fetchList, storeWarehouse, putWarehouse, delWarehouse } from '@/services/warehouse'
import { message } from 'antd';
export default {
    namespace: 'warehouse',

    state: {
        listData: [],
        total: null,
        query: {
            name: ''
        },
        modalInitValues: {
            name: '',
            desc: '',
            created_at: null,
        },
        modalType: 'create',
        modalVisible: false,
        confirmLoading: false,
    },

    effects: {
        * fetch({ payload = { page: 1, pageSize: 10 } }, { call, put }) {
            const response = yield call(fetchList, payload);
            if (response.code === 0) {
                yield put({
                    type: 'updateState',
                    payload: {
                        listData: response.list,
                        total: response.total
                    }
                })
            }
        },
        * addWarehouse({ payload }, { call, put }) {
            const response = yield call(storeWarehouse, payload);
            if (response.code === 0) {
                message.success('新增成功');
                yield put({
                    type: 'hideModal'
                });
                yield put({
                    type: 'fetch'
                })
            }
        },
        * editWarehouse({ payload }, { call, put }) {
            const response = yield call(putWarehouse, payload);
            if (response.code === 0) {
                message.success('更新成功');
                yield put({
                    type: 'hideModal'
                });
                yield put({
                    type: 'fetch'
                })
            }
        },
        * delWarehouse({ payload }, { call, put }) {
            const response = yield call(delWarehouse, payload);
            if (response.code === 0) {
                message.success('删除成功');
                yield put({
                    type: 'fetch'
                })
            }
        }
    },
    
    reducers: {
        updateState(state, { payload }) {
            return {
              ...state,
              ...payload
            };
        },
        showModal(state, { payload }) {
            return {
                ...state,
                ...payload,
                modalVisible: true,
            }
        },
        hideModal(state) {
            return {
                ...state,
                modalVisible: false,
            }
        }
    },
    subscriptions: {
        setup({dispatch, history}) {
            history.listen(({ pathname }) => {
              if (pathname === '/members') {
                 dispatch({type: 'fetch'})
              }
            })
         }
    }
}